package com.njcb.ams.service;

import com.njcb.ams.factory.domain.AppContext;
import com.njcb.ams.portal.SysBaseDefine;
import com.njcb.ams.repository.dao.AuthRUserRoleDAO;
import com.njcb.ams.repository.dao.CommUserInfoDAO;
import com.njcb.ams.repository.entity.AuthRUserRole;
import com.njcb.ams.repository.entity.CommUserInfo;
import com.njcb.ams.support.security.bo.SecurityUser;
import com.njcb.ams.util.AmsAssert;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author srxhx207
 */
@Service
public class UserManageService {
    @Autowired
    private CommUserInfoDAO userInfoDAO;
    @Autowired
    private AuthRUserRoleDAO authRUserRoleDAO;
    @Autowired
    private SessionRegistry sessionRegistry;

    public static UserManageService getInstance() {
        return AppContext.getBean(UserManageService.class);
    }

    public void registerUser(CommUserInfo userInfo) {
        AmsAssert.notNull(userInfo.getLoginName(), "用户登录名不能为空");
        userInfo.setStatus(SysBaseDefine.USER_STATUS_NORMAL);
        String password = PasswordEncoderFactories.createDelegatingPasswordEncoder().encode(userInfo.getPassWord());
        userInfo.setPassWord(password);
        userInfo.setOrgId(1);
        userInfoDAO.insert(userInfo);
        AuthRUserRole authRUserRole = new AuthRUserRole();
        authRUserRole.setRoleId(1);
        authRUserRole.setUserId(userInfo.getId());
        authRUserRoleDAO.insert(authRUserRole);
    }

    public List<CommUserInfo> queryUser(CommUserInfo userInfo) {
        return userInfoDAO.selectBySelective(userInfo);
    }

    /**
     * 新增用户默认密码 88888888
     *
     * @param userInfo
     */
    public void saveUserInfo(CommUserInfo userInfo) {
        AmsAssert.notNull(userInfo.getLoginName(), "用户登录名不能为空");
        if (null == userInfo.getId()) {
            //新增
            //用户登录号唯一性校验：
            CommUserInfo orgUserInfo = userInfoDAO.findByLoginName(userInfo.getLoginName());
            AmsAssert.isNull(orgUserInfo, "用户登录号[" + userInfo.getLoginName() + "]已存在");
            //关联员工号唯一性校验：
            CommUserInfo EmpNoUserInfo = userInfoDAO.findByLoginName(userInfo.getEmpNo());
            AmsAssert.isNull(EmpNoUserInfo, "关联员工号[" + userInfo.getEmpNo() + "]已存在");

            String password = PasswordEncoderFactories.createDelegatingPasswordEncoder().encode(SysBaseDefine.DEFAULT_PASSWORD);
            userInfo.setPassWord(password);
        } else {
            //修改
            userInfo.setPassWord(userInfoDAO.selectByPrimaryKey(userInfo.getId()).getPassWord());
        }
        userInfoDAO.saveOrUpdateByPrimaryKey(userInfo);
    }

    public int resetPwd(String loginName, String newPassword) {
        int flag = 0;
        if (StringUtils.isNotEmpty(loginName)) {
            CommUserInfo user = userInfoDAO.findByLoginName(loginName);
            String password = newPassword;
            password = PasswordEncoderFactories.createDelegatingPasswordEncoder().encode(password);
            user.setPassWord(password);
            flag = userInfoDAO.updatePassword(user);
            removeAuthCache(loginName);
        }
        return flag;
    }

    public void unlockUser(String loginName) {
        removeAuthCache(loginName);
    }

    public void removeUserInfo(CommUserInfo userInfo) {
        userInfoDAO.deleteByPrimaryKey(userInfo.getId());
    }

    public void removeAuthCache(String loginName) {
//		logger.debug("清除用户权限缓存{}",loginName);
//		EhCacheManager cacheManager = (EhCacheManager) ContextUtil.getBean("shiroCacheManager");
//		Cache<String,Object> cache =  cacheManager.getCache("authenticationCache");
//		cache.remove(loginName);
//		logger.debug("清除密码重试缓存{}",loginName);
//		Cache<String, AtomicInteger> passwordRetryCache = cacheManager.getCache("passwordRetryCache");
//		passwordRetryCache.remove(loginName);
    }

    /**
     * 剔除在线用户
     * @param loginName
     */
    public void kickOutOnlineUser(String loginName) {
        AmsAssert.notNull(loginName, "用户登录名称不能为空");
        SecurityUser securityUser = new SecurityUser();
        securityUser.setLoginName(loginName);
        //查询所有未失效会话
        List<SessionInformation> sessions = sessionRegistry.getAllSessions(securityUser, false);
        for (SessionInformation session : sessions) {
            session.expireNow();
        }
    }


    /**
     * 清除用户会话
     * @param loginName
     */
    public void clearUserSession(String loginName) {
        AmsAssert.notNull(loginName, "用户登录名称不能为空");
        SecurityUser securityUser = new SecurityUser();
        securityUser.setLoginName(loginName);
        //查询所有未失效会话
        List<SessionInformation> sessions = sessionRegistry.getAllSessions(securityUser, false);
        for (SessionInformation session : sessions) {
            sessionRegistry.removeSessionInformation(session.getSessionId());
        }
    }
}
